/**
 * www.ewanse.com.
 * Copyright (c) 2009-2016 All Rights Reserved.
 */
package com.sunday.bo;

import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sunday.constant.UserConstant;
import com.sunday.dao.UserDOMapper;
import com.sunday.enums.UserTypeEnum;
import com.sunday.form.UserQueryForm;
import com.sunday.pojo.UserDO;
import com.sunday.result.BaseResult;
import com.sunday.result.BizException;
import com.sunday.result.enums.BizResultCodeEnum;

/**
 * 用户BO
 * @author donghongli
 * @version $Id: UserBO.java, v 0.1 2016年1月6日 下午1:47:03 donghongli Exp $
 */
@Service
public class UserBO {

    @Autowired
    private UserDOMapper userDOMapper;

    public BaseResult<List<UserDO>> queryList(UserQueryForm form) {
        List<UserDO> userList = userDOMapper.list(form);
        int totalRows = userDOMapper.count(form);
        return new BaseResult<List<UserDO>>(userList, form, totalRows);
    }

    public UserDO find(Long userId) {
        return userDOMapper.selectByPrimaryKey(userId);
    }

    public void delete(Long userId) {
        userDOMapper.deleteByPrimaryKey(userId);
    }

    public void saveOrUpdate(UserDO userDO) {
        if (userDO.getId() == null) {
            Date date = new Date();
            userDO.setPassword(DigestUtils.md5Hex(UserConstant.DEFAULT_PWD));
            userDO.setType(UserTypeEnum.SELLER.getCode());
            userDO.setAreaId(0);
            userDO.setCreated(date);
            userDO.setModifyd(date);
            userDO.setLastLoginIp(StringUtils.EMPTY);
            userDO.setLastLoginTime(date);
            userDOMapper.insertSelective(userDO);
        } else {
            UserDO oldDO = userDOMapper.selectByPrimaryKey(userDO.getId());
            if (oldDO == null) {
                throw new BizException(BizResultCodeEnum.NOT_EXISTED, "要修改的数据不存在，goodsId="
                                                                      + userDO.getId());
            }
            userDOMapper.updateByPrimaryKeySelective(userDO);
        }
    }
}
